<script setup lang="ts">
    import type { ImageBody } from '@/services/type';
    import { useImgPreviewStore } from '@/stores/preview';

    const { body } = defineProps<{ body: ImageBody }>();
    const imgPreviewStore = useImgPreviewStore();

    // 核心就是的到高度，产生明确占位防止图片加载时页面抖动
    const getImageHeight = () => {
        const { width, height } = body;
        return formatImage(width, height);
    }

    // 图片尺寸格式化
    const formatImage = (width: number, height: number) => {
        // 初始化宽高
        const { maxWidth, maxHeight } = { 
            maxWidth: 200, 
            maxHeight: 150
        };
        if (width < maxWidth && height < maxHeight) { // 小： 如果图片宽高都小于最大宽高，直接返回原高度
            return height;
        } else if (width > height) { // 宽： 根据宽度等比缩放
            return (maxWidth / width) * height;
        } else if (width === height || width < height) { // 窄：返回最大高度
            return maxHeight;
        }
        return maxHeight;
    }
</script>
<template>
    <div 
        class="image" 
        :style="{ height: getImageHeight() + 'px' }"
        @click="imgPreviewStore.show(body.url)"
    >
        <img :src="body.url" draggable="false" style="width: 100%; height: 100%;" />
    </div>
</template>
<style lang="css" scoped>
    .image {
        cursor: pointer;
    }
</style>